package com.hxx.day5;

import org.junit.Test;

import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class TestDemo1 {
    public static void main(String[] args) {
        Set set = new TreeSet();
        set.add(9);
        set.add(2);
        set.add(5);
        set.add(1);
        set.add(1);
        System.out.println(set);

        for (Object o : set) {
            System.out.println(o);
        }
        System.out.println("---------");
        set.stream().forEach(System.out::println);
        System.out.println("---------");
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
        System.out.println("---------");
        set.stream().iterator().forEachRemaining(System.out::println);
    }

    @Test
    public void test1() {//实现Comparable接口完成对某个属性的排序
        Set set = new TreeSet();
        set.add(new Person(5, "张三"));
        set.add(new Person(11, "王五"));
        set.add(new Person(2, "赵六"));
        set.add(new Person(3, "张三"));

        System.out.println(set);
    }
    @Test
    public void test2() {
        //实现Comparator接口完成对某个属性的排序,
        // 匿名内部类
        Set set = new TreeSet(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof User && o2 instanceof User) {
                    User u1 = (User) o1;
                    User u2 = (User) o2;
                    return u2.getId() - u1.getId();
                }
                return 0;
            }
        });
        set.add(new User(5, "张三"));
        set.add(new User(11, "王五"));
        set.add(new User(2, "赵六"));
        set.add(new User(3, "张三"));

        System.out.println(set);
    }
    @Test
    public void test3() {
        //实现Comparator接口完成对某个属性的排序,
        // 匿名内部类
        Set set = new TreeSet((x,y)->((User)x).getId()-((User)y).getId());
        set.add(new User(5, "张三"));
        set.add(new User(11, "王五"));
        set.add(new User(2, "赵六"));
        set.add(new User(3, "张三"));

        System.out.println(set);
    }
}




















